package com.example.administrator.OnLine;


import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.SDKInitializer;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.zyzpp.bean.SocketBean;
import com.zyzpp.service.MyService;
import com.zyzpp.socketTest.SocketTest;



public class MainActivity extends AppCompatActivity {
    //private TextureMapView mMapView;
    private BaiduMap mBaiduMap;
    MapView mMapView = null;
    private Spinner spinner;
    private static String[] mArrayString = null;
    private ArrayAdapter<String> mArrayAdapter;
    private TextView textView;
    private String dlog="定位中...";
    private String error="服务器参数出错";
    public static int count=1;
    public static int count2=1;
    Handler handler;
    SocketTest socketTest;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        //初始化title的TextView
        tilteInit();
        //获取地图控件引用
//        mMapView = (TextureMapView) findViewById(R.id.mTexturemap);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        //初始化下拉框视图
        sinnerStart();
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        SocketBean bean = (SocketBean) msg.obj;
                        try {
                            //百度地图
                            showCurrentPosition(bean);
                            //动态显示信息
                            tiltetext(bean);
                        }catch (Exception e){
                            Log.e("日志","接受定位信息出错");
                        }
                        break;
                    case 0:
                        String data=(String)msg.obj;
                        textView.setText(data);
                        break;
                }
            }
        };
        //启动socket，该方法一定写在handler之后
        socketTest=new SocketTest(handler);
    }
    @Override
    protected void onStart() {
        super.onStart();
        count=1;
        count2=1;
    }
    /**定位**/
    public void showCurrentPosition(SocketBean location){
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 构造定位数据
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();
        // 设置定位数据
        mBaiduMap.setMyLocationData(locData);
        //COMPASS罗盘态LocationMode.NORMAL 普通态LocationMode.FOLLOWING;//定位跟随态
        MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.COMPASS;
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        BitmapDescriptor mCurrentMarker= BitmapDescriptorFactory.fromResource(R.drawable.dingwei);
        //设置
        MyLocationConfiguration config = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
        mBaiduMap.setMyLocationConfiguration(config);
    }
    /**
     * 下拉框
     */
    private void sinnerStart(){
        spinner=(Spinner)findViewById(R.id.test_spinner);
//        初始化spinner中显示的数据
        mArrayString = new String[]{"普通地图","卫星地图","实时路况图","关闭路况","实时模式","普通模式","延时模式","退出登录","开发者"};
//        adapter_mytopactionbar_spinner改变了spinner的默认样式
        mArrayAdapter=new ArrayAdapter<String>(this,R.layout.adapter_mytopactionbar_spinner,mArrayString){
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                if (convertView == null){
//                    设置spinner展开的Item布局
                    convertView = getLayoutInflater().inflate(R.layout.adapter_mytopactionbar_spinner_item, parent, false);
                }
                TextView spinnerText=(TextView)convertView.findViewById(R.id.spinner_textView);
                spinnerText.setText(getItem(position));
                return convertView;
            }
        };
        spinner.setAdapter(mArrayAdapter);
//        spinner设置监听
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                        break;
                    case 1:
                        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                        break;
                    case 2:
                        mBaiduMap.setTrafficEnabled(true);
                        break;
                    case 3:
                        mBaiduMap.setTrafficEnabled(false);
                        break;
                    case 4:
                        socketTest.setOptionTime(100*1000);
                        Toast.makeText(MainActivity.this,"实时模式:频率10s/c",Toast.LENGTH_SHORT).show();
                        break;
                    case 5:
                        socketTest.setOptionTime(300*1000);
                        Toast.makeText(MainActivity.this,"普通模式:频率30s/c",Toast.LENGTH_SHORT).show();
                        break;
                    case 6:
                        socketTest.setOptionTime(600*1000);
                        Toast.makeText(MainActivity.this,"延时省流:频率60s/c",Toast.LENGTH_SHORT).show();
                        break;
                    case 7:
                        exitOnline();
                        break;
                    case 8:
                        updateApp();
                        break;
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    /**
     * 初始化TextView
     */
    private void tilteInit(){
        textView=(TextView)findViewById(R.id.map_title);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNormalDialog("位置", dlog);
            }
        });
    }
    /**
     * TextView动态改变
     */
    private void tiltetext(SocketBean location){
        StringBuffer text=new StringBuffer();
        if(location.getAddr()!=null){
            text.append(location.getAddr());
        }
        if(location.getLocationDescribe()!=null){
            text.append(location.getLocationDescribe());
        }
        textView.setText(text.toString());
        if(location.getHeight()!=null){
            text.append("\n"+location.getHeight());
        }
        if(location.getSpeed()!=null){
            text.append("\n"+location.getSpeed());
        }
        dlog=text.toString();
    }
    /**
     * 退出软件
     */
    private void exitOnline(){
        new AlertDialog.Builder(MainActivity.this)
                .setIcon(R.mipmap.ico)
                .setTitle("退出OnLine")
                .setMessage("是否确认退出登录？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //本地数据
                        SharedPreferences sharedPreferences=getApplication().getSharedPreferences("user",
                                Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putInt("online",0);
                        editor.commit();
                        //跳转屏幕
                        Intent intent=new Intent(MainActivity.this,StarActivity.class);
                        startActivity(intent);
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this,"明智的选择",Toast.LENGTH_SHORT).show();
                    }
                })
                .show();
    }
    /**
     * 物理返回
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 检查更新
     */
    private void updateApp(){
        new AlertDialog.Builder(MainActivity.this)
                .setIcon(R.mipmap.ico)
                .setTitle("OnLine")
                .setMessage(("\n开发者：keepsunsun@qq.com\n\n欢迎联系、合作、学习！"))
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }
    /**
     * 对话框展示位置信息
     */
    private void showNormalDialog(String title,String message){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(MainActivity.this);
        normalDialog.setIcon(R.drawable.top);
        normalDialog.setTitle(title);
        normalDialog.setMessage(message);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog.show();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        //service启动
        Intent intent =new Intent(this, MyService.class);
        startService(intent);
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
}
